package web.forms;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;

public class LoginForm extends ActionForm{
	private static final long serialVersionUID = 8481085161151530999L;
	
	private String usuario;
 	private String password;
 	private final static int[] ELEMENTS_NOT_ALLOWED_PASSWORD = {241,209}; /* � , � */
 	private final static int INIT_ELEMENT = 97; /* LETRA a */
 	private final static int FINAL_ELEMENT = 122; /* LETRA z */

 
 
 	public String getUsuario() {
		return usuario;
	}
	public void setUsuario(String usuario) {
		this.usuario = usuario;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}

	private boolean isNumber(char caracter) {
		if (caracter>=48 && caracter<=57) {
			return true;
		}
		return false;
	}

	private boolean isAllowChar(char caracter) {
		for (int i = 0 ; i < ELEMENTS_NOT_ALLOWED_PASSWORD.length ; i++) 
			if (ELEMENTS_NOT_ALLOWED_PASSWORD[i] == caracter )
			return false;		
		return true;
	}

	private boolean validarPassword(){
		for (int i = 0 ; i< this.password.length() ; i++) {
			if ( !(password.charAt(i)>=INIT_ELEMENT && 
				password.charAt(i)<=FINAL_ELEMENT && 
				isAllowChar(password.charAt(i)) ||
				isNumber(password.charAt(i)))) {
				return false;				
			}				
		}
		return true;
	}

	private boolean isUsuario() {
		for (int i = 0 ; i< this.usuario.length() ; i++) {
			if ( !(this.usuario.charAt(i)>=INIT_ELEMENT && 
					this.usuario.charAt(i)<=FINAL_ELEMENT && 
				isAllowChar(this.usuario.charAt(i)) ||
				isNumber(this.usuario.charAt(i)))) {				
				return false;				
			}				
		}
		return true;
	}

	public ActionErrors validate(ActionMapping mapping,
								HttpServletRequest request) {
		
		ActionErrors errors = new ActionErrors();
	
		if (this.usuario == null || !isUsuario()) {
				
			errors.add("ErrorLogin",new ActionError("error.login.usuario"));
		}
		if ( this.password == null || !validarPassword()) {
				
			errors.add("ErrorLogin",new ActionError("error.login.password"));
		}
		return errors;
 	}


 
}
